package com.example.springboot4.system.web.controller;

import cn.hutool.http.HttpStatus;
import com.example.springboot4.system.config.FileConfigProperties;
import com.example.springboot4.system.constant.FieldConstants;
import com.example.springboot4.system.exception.ServiceException;
import com.example.springboot4.system.model.Params;
import com.example.springboot4.system.model.Result;
import com.example.springboot4.system.util.FileUploadUtils;
import com.example.springboot4.system.util.FileUtils;
import com.example.springboot4.system.util.ServletUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 通用 工具类
 *
 * @author 宋义州
 * @since 2024/1/16 13:44
 */
@Slf4j
@Tag(name = "通用工具类")
@RestController
@RequestMapping("/api/common")
public class CommonController {

    /**
     * 文件分隔符
     */
    private static final String FILE_DELIMITER = ",";

    /**
     * 通用下载请求、下载提前放到服务器配置的文件目录里的
     *
     * @param fileName 文件名称
     * @param delete   是否删除
     */
    @Operation(summary = "通用下载请求", description = "下载提前放到服务器配置的文件目录里的文件", security = @SecurityRequirement(name = HttpHeaders.AUTHORIZATION))
    @Parameters({
            @Parameter(name = "fileName", description = "文件名称", schema = @Schema(implementation = String.class), required = true),
            @Parameter(name = "delete", description = "是否删除", schema = @Schema(implementation = Boolean.class), required = true)
    })
    @ApiResponse(responseCode = "200", description = "操作成功!", content = @Content(mediaType = "application/json", schema = @Schema(implementation = Result.class)))
    @GetMapping("/download")
    public void fileDownload(@RequestParam String fileName, @RequestParam Boolean delete, HttpServletResponse response) {
        try {
            boolean checked = FileUtils.checkAllowDownload(fileName);
            if (!checked) {
                throw new Exception(String.format("文件名称(%s)非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = FileConfigProperties.getDownloadPath() + fileName;
            //
            //response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete) {
                boolean deleteFile = FileUtils.deleteFile(filePath);
                log.info("删除文件结果：{}", deleteFile);
            }
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 上传文件
     *
     * @param file 文件
     * @return Result
     */
    @Operation(summary = "上传文件", description = "上传文件", security = @SecurityRequirement(name = HttpHeaders.AUTHORIZATION))
    @ApiResponse(responseCode = "200", description = "操作成功!", content = @Content(mediaType = "application/json", schema = @Schema(implementation = Result.class)))
    @PostMapping("/upload")
    public Result<?> upload(@Parameter(name = "file", description = "文件", schema = @Schema(implementation = MultipartFile.class), required = true)
                            @RequestBody MultipartFile file) {
        try {
            if (Objects.isNull(file) || file.isEmpty()) {
                throw ServiceException.create(HttpStatus.HTTP_BAD_REQUEST, "上传的文件为空！");
            }
            // 上传文件路径
            String filePath = FileConfigProperties.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = getUrl() + fileName;

            Params params = new Params();
            params.put("url", url);
            params.put("fileName", fileName);
            params.put("newFileName", FileUtils.getName(fileName));
            params.put("originalFilename", file.getOriginalFilename());
            return Result.success(params);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 通用上传请求（多个）
     *
     * @param files 文件
     * @return Result
     */
    @Operation(summary = "通用上传请求", description = "通用上传请求（多个）", security = @SecurityRequirement(name = HttpHeaders.AUTHORIZATION))
    @ApiResponse(responseCode = "200", description = "操作成功!", content = @Content(mediaType = "application/json", schema = @Schema(implementation = Result.class)))
    @PostMapping("/uploads")
    public Result<?> uploadFiles(@Parameter(name = "files", description = "文件", schema = @Schema(implementation = MultipartFile.class), required = true)
                                 @RequestBody List<MultipartFile> files) {
        try {
            // 上传文件路径
            String filePath = FileConfigProperties.getUploadPath();
            List<String> urls = new ArrayList<>();
            List<String> fileNames = new ArrayList<>();
            List<String> newFileNames = new ArrayList<>();
            List<String> originalFilenames = new ArrayList<>();

            for (MultipartFile file : files) {
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file);
                String url = getUrl() + fileName;
                urls.add(url);
                fileNames.add(fileName);
                newFileNames.add(FileUtils.getName(fileName));
                originalFilenames.add(file.getOriginalFilename());
            }

            Params params = new Params();
            params.put("urls", StringUtils.join(urls, FILE_DELIMITER));
            params.put("fileNames", StringUtils.join(fileNames, FILE_DELIMITER));
            params.put("newFileNames", StringUtils.join(newFileNames, FILE_DELIMITER));
            params.put("originalFilenames", StringUtils.join(originalFilenames, FILE_DELIMITER));
            return Result.success(params);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 本地资源通用下载, 下载由系统上传的文件
     *
     * @param resource 资源地址
     * @param response 响应
     */
    @Operation(summary = "本地资源通用下载", description = "本地资源通用下载, 下载由系统上传的文件", security = @SecurityRequirement(name = HttpHeaders.AUTHORIZATION))
    @ApiResponse(responseCode = "200", description = "操作成功!", content = @Content(mediaType = "application/json", schema = @Schema(implementation = Result.class)))
    @GetMapping("/download/resource")
    public void resourceDownload(@Parameter(name = "resource", description = "资源地址", schema = @Schema(implementation = String.class), required = true)
                                 @RequestParam String resource, HttpServletResponse response) {
        try {
            if (!FileUtils.checkAllowDownload(resource)) {
                throw new Exception(String.format("资源文件(%s)非法，不允许下载。 ", resource));
            }
            // 本地资源路径
            String localPath = FileConfigProperties.getProfile();
            // 数据库资源地址
            String downloadPath = localPath + StringUtils.substringAfter(resource, FieldConstants.RESOURCE_PREFIX);
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载文件失败:{}", e.getMessage());
        }
    }

    /**
     * 获取完整的请求路径，包括：域名，端口，上下文访问路径
     *
     * @return 服务地址
     */
    public String getUrl() {
        HttpServletRequest request = ServletUtils.getRequest();
        StringBuffer url = request.getRequestURL();
        String contextPath = request.getServletContext().getContextPath();
        return url.delete(url.length() - request.getRequestURI().length(), url.length()).append(contextPath).toString();
    }

}
